#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   testVScode.py
@Time    :   2020/06/18 23:19:39
@Author  :   Qing Bei
@Version :   1.0
@Contact :   1013575196@qq.com
@License :   (C)Copyright 2017-2018, Liugroup-NLPR-CASIA
@Desc    :   None
                       _oo0oo_
                      o8888888o
                      88" . "88
                      (| -_- |)
                      0\  =  /0
                    ___/`---'\___
                  .' \\|     |// '.
                 / \\|||  :  |||// \
                / _||||| -:- |||||- \
               |   | \\\  - /// |   |
               | \_|  ''\---/''  |_/ |
               \  .-\__  '-'  ___/-. /
             ___'. .'  /--.--\  `. .'___
          ."" '<  `.___\_<|>_/___.' >' "".
         | | :  `- \`.;`\ _ /`;.`/ - ` : | |
         \  \ `_.   \_ __\ /__ _/   .-` /  /
     =====`-.____`.___ \_____/___.-`___.-'=====
                       `=---='


     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

           佛祖保佑       永不宕机     永无BUG

'''
# # here put the import lib
import numpy as np
import pandas as pd

# 用户类
class User(object):

  def __init__(self, money=1000):#boughtDataFrame):
    self.__userName = input('请输入用户名')
    self.__userPwd = input('请输入密码')
    self.__money = money

  def setUserName(self, newName):
    self.__userName = newName

  def setUserPwd(self, newPwd):
    self.__userPwd = newPwd

  def getUserMoney(self):
    return int(self.__money)

  def Register(self):
    global userFile, shangpingFile
    with open(userFile, 'a+',encoding='utf-8', buffering=1) as Rg:
      userList1 = Rg.readlines()
      UserDic1 = {}
      for line in userList1:
        User1 = line.rstrip('\n').split('+')
        UserDic1['{}'.format(User1[0])] = User1[1]
      if self.__userName not in UserDic1 and self.__userName != 'exit':
        RgPwd = input('请输入注册登陆密码：')
        # 不在名单内，写入注册名单
        if Rg.write(self.__userName + '+' + RgPwd + '+' + str(self.__money) + '\n'):
          self.__userPwd = RgPwd
          print('注册成功')
          return "Success"
      # 在名单内，重新注册账号
      else:
        if self.__userName == 'exit':
          print('用户不能输入eixt作为用户名')
          return "exit"
        else:
          print('用户名已存在，请重新输入注册用户名:')
          return "User exists"

  def Login(self):
    userFile = 'G:\\hello\\.vscode\\SanChuangStudy\\user.txt'
    shangpingFile = 'G:\\hello\\.vscode\\SanChuangStudy\\shangping.xlsx'
    with open(userFile, 'r', encoding='utf-8',buffering=1) as lg:
      userlist2 = lg.readlines()
      UserDic2 = {}
      for line in userlist2:
        User2 = line.rstrip('\n').split('+')
        UserDic2['{}'.format(User2[0])] = User2[1]
      if self.__userName in UserDic2:
        if self.__userPwd == UserDic2[self.__userName]:
          print('登陆成功!')
          return "yes"
        else:
          return "pwd failed"
      else:
          print("用户不存在,请先注册")
          return "zhuce"
      return

  def SanChuangShop(self):
    userFile = 'G:\\hello\\.vscode\\SanChuangStudy\\user.txt'
    shangpingFile = 'G:\\hello\\.vscode\\SanChuangStudy\\shangping.xlsx'
    print('欢迎来到三乐超市，以下为商品列表:')
    boughtDic = {}
    tmp = '1'# 继续购买判别 Flag
    while tmp == '1':
      # 设置列对齐
      pd.set_option('display.unicode.ambiguous_as_wide', True)
      pd.set_option('display.unicode.east_asian_width', True)

      # 读取商品详情
      df = pd.read_excel(r'G:\\hello\\.vscode\\SanChuangStudy\\shangping.xlsx',\
          usecols={'商品编号':str, '商品名称':str, '单价(元/斤)':int, '存货量(斤、个)':int})
      print(df[:],end='\n')

      # 根据 dataframe构建Dict1('编号':单价) Dict2('编号':'存货量') Dict3('编号':'名称')
      dc1 = {col:df[col].tolist() for col in df.columns}
      DictKey = dc1['商品编号']
      Dict1Value = dc1['单价(元/斤)']
      Dict2Value = dc1['存货量(斤、个)']
      Dict3Value = dc1['商品名称']
      # 主要是因为散列表快，但是消耗内存是缺陷
      Dict1 = dict(zip(DictKey, Dict1Value))  # 用于根据商品编号查询单价
      Dict2 = dict(zip(DictKey, Dict2Value))  # 用于根据商品编号查询存货量和修改存货量
      Dict3 = dict(zip(DictKey, Dict3Value))  # 用于根据编号查询商品名称

    #已购买商品清单
      print('请输入购买的商品编号和数量,如F00001 2表示购买编号为F00001商品2斤/个')
      #SNum:商品编号 number:购买商品数量
      SNum, number = input().split()
      Number = int(number)
      # 用户钱足够并且用户选择继续购买, 单价你也可以用float(Dict1[SNum])
      if int(self.getUserMoney()) >= Number*int(Dict1[SNum])  and tmp == '1' and SNum != 'exit' \
        and SNum!=[] and number!=[]:
          # 用户需求数量小于等于商品数量
          if Number <= Dict2[SNum]:
              # 加入已购清单
              # 购买商品不在boughtDic字典内
              if Dict3[SNum] not in boughtDic:
                boughtDic['{}'.format( Dict3[SNum] )] = Number

              # 购买商品在boughtDic字典内
              else:
                OldNum = int(boughtDic['{}'.format( Dict3[SNum] )])
                boughtDic['{}'.format( Dict3[SNum] )] = OldNum + Number

              # 修改(替换)user.txt文件用户的所剩金额
              file_data = ""
              oleStr = self.__userName + '+' + self.__userPwd + '+' + str(self.__money)
              newStr = self.__userName + '+' + self.__userPwd + '+' + str(self.__money - int(Number * int(Dict1[SNum]) ))
              with open(userFile,'r',encoding='utf-8', buffering=1) as f:
                for line in f:
                  if oleStr in line:
                    line = line.replace(oleStr, newStr)
                  file_data += line
              with open(userFile, 'w', encoding='utf-8')as f:
                f.write(file_data)

              tmp = input('输入1继续购买,输入其他退出系统')

              # Dict2内将对应商品存货数量减去number
              Dict2[SNum] -= Number
              # 将修改商品数量修改到df(即dataframe)中
              df['存货量(斤、个)'] = Dict2.values()
              # 修改完数量之后写回excel表格,需要安装openpyxl
              # 默认使用openpyxl进行传输数据（pip3 install openpyxl -i 国内源）
              df.to_excel(shangpingFile)

          else:
              print( '商品{}库存不足'.format( Dict1[SNum] ) )

      # 钱不够
      if int(self.getUserMoney()) < Number * int( Dict1[SNum] ) and tmp == '1' and SNum != 'exit':
        print('余额不足无法购买')
        tmp = input('输入1继续选择其他商品购买,输入exit退出系统')

      # 用户输入exit或其他非1的东西退出系统
      if tmp == 'exit' or SNum == 'exit':
        print('用户退出系统,购买清单如下:')
        print(boughtDic)
        return

      if tmp != '1' and tmp != 'exit':
        print('用户退出系统,购买清单如下:')
        print(boughtDic)
        return

def main():
  # windows下用\\ linux下用//
  userFile = 'G:\\hello\\.vscode\\SanChuangStudy\\user.txt'
  shangpingFile = 'G:\\hello\\.vscode\\SanChuangStudy\\shangping.xlsx'
  user = User()
  count = 1
  # 三次输入密码的机会
  tmp1 = user.Login()
  if tmp1 == "yes":
    user.SanChuangShop()
  if tmp1 == "pwd failed":
    while count < 3:
      print('密码错误,请重新输入:')
      user.setUserPwd(input())
      tmp1 = user.Login()
      count += 1
      # 密码输入三次错误，退出系统, 之后可以考虑加个锁定用户什么的，如在用户名前面内加个符号
      if count==3:
        print('累积三次输入密码错误,系统退出')
        return
      if tmp1 == 'yes':
        break
    user.SanChuangShop()

  #进入注册界面
  if tmp1 == "zhuce":
    # 输入exit退出
    tmp2 = user.Register()
    # 注册成功
    if tmp2 == "Success":
      user.SanChuangShop()
      # return
    # 用户名已存在
    elif tmp2 == "User exists":
      print('注册失败，用户名已存在')
      return
    # 输入"exit"或其他则退出系统
    else:
      print('系统退出')
      return

if __name__ == "__main__":
    main()